import * as Koa from 'koa';
import getConnection from '../mysql/connection';
import { generateSql } from './sql';

/**
 * 查询
 * @param {*} params 查询条件
 */
export async function getRoles(ctx: Koa.Context, params?: Object, options?: any)  {
  let connection: any = null;
  try {
    const db = ctx.dbPool;
    connection = await getConnection(db);
    const sql = generateSql("role", "query", params);
    if (!sql) return { msg: "生成sql语句错误", success: false };
    const [result] = await connection.execute(sql);

    // 将menu id 转为名称
    if (options?.needRoleName) {
      const menuSql = generateSql("menu", "query", {});
      if (!menuSql) return { msg: "生成sql语句错误", success: false };
      const [menuResult] = await connection.execute(menuSql);
      result.forEach((item: any) => {
        if (item.menuIds) {
          const arr = item.menuIds.split(",");
          const menuNames = arr.map((id: string) => {
            return menuResult.find((menu: any) => menu.id == id)?.title || "";
          });
          item.menuNames = menuNames.join(",");
        }
      });
    }
    
    return { success: true, data: result };
  } catch (error) {
    return { msg: error.sqlMessage || "", success: false };
  } finally {
    if (connection) connection.release();
  }
}

/**
 * 删除
 * @param {*} id ID
 */
export async function delRole(ctx: Koa.Context, params: Object) {
  let connection: any = null;
  try {
    const db = ctx.dbPool;
    connection = await getConnection(db);
    const sql = generateSql("role", "delete", params);
    if (!sql) return { success: false };
    await connection.execute(sql);
    return { success: true };
  } catch (error) {
    return { msg: error.sqlMessage || "", success: false };
  } finally {
    if (connection) connection.release();
  }
}

/**
 * 增加
 * @param {*}
 */
export async function addRole(ctx: Koa.Context, data: any)  {
  let connection: any = null;
  try {
    if (!data) return { success: false };
    const db = ctx.dbPool;
    connection = await getConnection(db);
    const sql = generateSql("role", "insert", data);
    if (!sql) return { msg: "生成sql语句错误", success: false };
    await connection.execute(sql, Object.values(data));
    return { success: true };
  } catch (error) {
    return { msg: error.sqlMessage || "", success: false };
  } finally {
    if (connection) connection.release();
  }
}

/**
 * 更新
 * @param {*}
 */
export async function updateRole(ctx: Koa.Context, data: any)  {
  let connection: any = null;
  try {
    if (!data?.rid) return { msg: "角色ID不能为空", success: false };
    const db = ctx.dbPool;
    connection = await getConnection(db);
    const sql = generateSql("role", "update", data);
    if (!sql) return { success: false };
    await connection.execute(sql, Object.values(data));
    return { success: true };
  } catch (error) {
    return { msg: error.sqlMessage || "", success: false };
  } finally {
    if (connection) connection.release();
  }
}

export async function searchRoleTotalNumbers(ctx: Koa.Context) {
  let connection: any = null;
  try {
    const db = ctx.dbPool;
    connection = await getConnection(db);
    const [result] = await connection.execute("SELECT COUNT(*) FROM role");
    return { success: true, data: result?.[0]?.["COUNT(*)"] || 0 };
  } catch (error) {
    return { msg: error.sqlMessage || "", success: false };
  } finally {
    if (connection) connection.release();
  }
}
